package com.sky.handler;


import com.sky.constant.MessageConstant;
import com.sky.entity.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器,处理项目中出现的异常业务逻辑
 * */

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /* *
     * 捕获业务异常
     * @param ex
     * */
    @ExceptionHandler(Exception.class)
    public Result ExceptionHandler(Exception ex) {
        log.error("异常信息: {}", ex.getMessage());
        return Result.error(StringUtils.hasLength(ex.getMessage())? ex.getMessage():MessageConstant.OPERATION_FAILED);
    }

    /* *
     * 捕获SQL异常
     * @param ex
     * */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        // 获取异常信息
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            // 按空格进行分割，获取用户名
            String[] arr = message.split(" ");
            // 第二个元素是重复的用户名
            String username = arr[2];
            String msg = username + MessageConstant.ALREADY_EXIST;
            return Result.error(msg);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
//    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
//    public ResponseEntity<String> handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
//        String message = String.format("参数 '%s' 类型不匹配，期望类型为 %s", ex, ex.getMessage());
//        return ResponseEntity.badRequest().body(message);
//    }
//}
